﻿using SevenZip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FtpFileBackup
{
    public static class SevenZipTool
    {
        static SevenZipTool()
        {
            // Toggle between the x86 and x64 bit dll
            var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Environment.Is64BitProcess ? "x64" : "x86", "7z.dll");
            SevenZipBase.SetLibraryPath(path);
        }
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="inputpath">压缩文件</param>
        /// <param name="outputpath">解压后文件</param>
        public static void Compress(string inputpath, string outputpath)
        {
            using (FileStream ostream = new FileStream(outputpath, FileMode.Create, FileAccess.Write))
            {
                using (FileStream istream = new FileStream(inputpath, FileMode.Open, FileAccess.Read))
                {
                    SevenZipCompressor compressor = new SevenZipCompressor();

                    // 这里可以输入多个文件名/流对
                    Dictionary<string, Stream> dict = new Dictionary<string, Stream> { { Path.GetFileName(inputpath), istream } };
                    compressor.CompressStreamDictionary(dict, ostream);
                }
            }
        }

        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="inputpath">待压缩文件</param>
        /// <param name="outputpath">压缩后文件</param>
        public static void Extract(string inputpath, string outputpath)
        {
            using (FileStream istream = new FileStream(inputpath, FileMode.Open, FileAccess.Read))
            {
                SevenZipExtractor extractor = new SevenZipExtractor(istream);
                extractor.ExtractArchive(outputpath);    // 全部解压到指定目录
                using (FileStream ostream = new FileStream(outputpath, FileMode.Create, FileAccess.Write))
                {
                    extractor.ExtractFile(0, ostream);        // 流式解压指定文件
                }
            }
        }
    }
}
